const BASE_URL =  '/api/';
import DeviceInfo from 'react-native-device-info';
export default class HttpUtil {

    /**
     * 利用 Promise 的 get 方式请求
     * @param url
     * @returns {Promise}
     */
    static get(url) {
      return Promise.race([
        new Promise((resolve, reject) => {
          fetch(global.variables.server + BASE_URL + url)
              .then(response => response.json())
              .then(result => resolve(result))
              .catch(error => reject(error))
        }),
        new Promise(function (resolve, reject) {
          setTimeout(() => reject(new Error('请求超时')), 10000);
        })
      ]);
    }
  
    /**
     * 利用 Promise 的 post 方式请求
     * @param url
     * @param params
     * @returns {Promise}
     */
    static post(url, params) {
      //(global.variables.server + BASE_URL + url);
      console.log(JSON.stringify(params))
      return Promise.race([
        new Promise((resolve, reject) => {
          fetch(global.variables.server + BASE_URL + url, {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'authorization': global.variables.authorization,
              'Device-Unique-Id':DeviceInfo.getUniqueId(),
              'model':"rk30sdk",
            },
            body: JSON.stringify(params)
          })
              .then(response => response.json())
              .then(result => resolve(result))
              .catch(error => reject(error))
        }),
        new Promise(function (resolve, reject) {
            setTimeout(() => reject(new Error('请求超时')), 20000);
        })
      ]);
    }

    static post2(url, params) {
      //console.log(global.variables.server + BASE_URL + url);
      return Promise.race([
        new Promise((resolve, reject) => {
          fetch('http://118.24.87.141:7070/asset' + BASE_URL + url, {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'authorization': global.variables.authorization,
              'Device-Unique-Id':DeviceInfo.getUniqueId(),
              'model':"rk30sdk",
            },
            body: JSON.stringify(params)
          })
              .then(response => response.json())
              .then(result => resolve(result))
              .catch(error => reject(error))
        }),
        new Promise(function (resolve, reject) {
            setTimeout(() => reject(new Error('请求超时')), 10000);
        })
      ]);
    }
}
